<?php
/**
 * 简历管理
 */

namespace app\v1_0\controller\company;

use app\common\logic\package\BaseArchiveLogic;
use app\common\logic\ResumeLogic;
use app\common\logic\ResumeParseLogic;
use app\common\model\BaseModel;
use app\common\model\Company;
use app\common\model\Member;
use app\common\model\ResumeActivate;
use app\common\model\ResumeEducation;
use app\v1_0\controller\home\Resume;
use EasyZip\ZipFile;
use think\cache\driver\Redis;
use Think\Db;
use think\Exception;
use think\File;

class ResumeManage extends \app\v1_0\controller\common\Base {

    public function _initialize() {
        parent::_initialize();
        if(!in_array(request()->action(),['test','google_plug_import','verify_secretkey','thirduploadzip','thirduploaddir',
            'thirduploadgetmobile','thirduploadgetmobilebatch','thirduploadgetmobilezip'])){
            $this->checkLogin(1);
            $this->interceptCompanyProfile();
            $this->interceptCompanyAuth();
        }
    }

    /**
     * 查询简历
     * @return void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index() {
        try{
            $education = input('post.edu/d', 0, 'intval');
            $experience = input('post.exp/d', 0, 'intval');
            $district = input('post.district/a', []);
            $jobcategory = input('post.jobcategory/a', []);
            $edu_nature = input('post.edu_nature/a',[]);
            $sex = input('post.sex/d', 0, 'intval'); // 性别
            $age = input('post.age/d', 0, 'intval'); // 年龄
            $tag = input('post.tag/a', []);
            $trade = input('post.trade/d', 0, 'intval');
            $major = input('post.major/d', 0, 'intval');
            $nature = input('post.nature/d', 0, 'intval');
            $minwage = input('post.minwage/d', 0, 'intval');
            $maxwage = input('post.maxwage/d', 0, 'intval');
            $settr = input('post.settr/d', 0, 'intval');
            $current_page = input('post.page/d', 1, 'intval');
            $pagesize = input('post.pagesize/d', 30, 'intval');

            $where['m.company_id'] = $this->company_profile['id'];
            $where['a.company_uid'] = $this->userinfo->uid;
            if ($education > 0) {//学历
                $where['r.education'] = ['=', $education];
            }
            if ($experience > 0) {
                switch ($experience) {
                    case 1: //无经验/应届生
                        $where['r.enter_job_time'] = ['=', 0];
                        break;
                    case 2://1年以下
                        $where['r.enter_job_time'] = ['>', strtotime('-1 year')];
                        break;
                    case 3://1年-2年
                        $where['r.enter_job_time'] = [['<=', strtotime('-1 year')], ['>', strtotime('-2 year')], 'and'];
                        break;
                    case 4://2年-3年
                        $where['r.enter_job_time'] = [['<=', strtotime('-2 year')], ['>', strtotime('-3 year')], 'and'];
                        break;
                    case 5://3年-5年
                        $where['r.enter_job_time'] = [['<=', strtotime('-3 year')], ['>', strtotime('-5 year')], 'and'];
                        break;
                    case 6://5年-10年
                        $where['r.enter_job_time'] = [['<=', strtotime('-5 year')], ['>', strtotime('-10 year')], 'and'];
                        break;
                    case 7://10年以上
                        $where['r.enter_job_time'] = [['<', strtotime('-10 year')], ['<>', 0], 'and'];
                        break;
                    default:
                        break;
                }
            }
            // 学历性质
            if($edu_nature){
                $uids = Member::where('company_id',$this->company_profile->id)->column('uid');
                $education = ResumeEducation::whereIn('uid',$uids)
                    ->when(in_array(2,$edu_nature),function($q){
                        $q->whereIn('school',model(BaseModel::class)->school_985);
                    })
                    ->when(in_array(3,$edu_nature),function($q){
                        $q->whereIn('school',model(BaseModel::class)->school_211);
                    })
                    ->field('rid,starttime,endtime')->select();
                $rids = [];
                foreach ($education as $value){
                    if(in_array(1,$edu_nature)){
                        $starttime = date('Y',$value['starttime']);
                        $endtime = date('Y',$value['endtime']);
                        if($endtime - $starttime >= 4){
                            $rids[] = $value['rid'];
                        }
                    }else{
                        $rids[] = $value['rid'];
                    }
                }
                $where['a.resume_id'] = ['in',$rids];
            }
            // 招聘平台
            if($recruit_platform = input('recruit_platform')){
                $rids = [];
                $uids = Member::where('company_id',$this->company_profile->id)->column('uid');
                $rids = \app\common\model\Resume::whereIn('uid',$uids)->where('platform',$recruit_platform)->column('id');
                $where['a.resume_id'] = ['in',$rids];
            }
            $join[] = ['resume r', 'a.resume_id=r.id', 'LEFT'];
            if (!empty($district) || !empty($jobcategory) || !empty($trade) || !empty($nature) || !empty($minwage)) {
                $join[] = ['ResumeIntention ris', 'ris.rid=r.id', 'LEFT'];
                if (!empty($district)) {//意向地区
                    if (isset($district[0]) && !empty($district[0])) {
                        $where['ris.district1'] = $district[0];
                    }
                    if (isset($district[1]) && !empty($district[1])) {
                        $where['ris.district2'] = $district[1];
                    }
                    if (isset($district[2]) && !empty($district[2])) {
                        $where['ris.district3'] = $district[2];
                    }
                }
                if (!empty($jobcategory)) {//意向职位
                    if (isset($jobcategory[0]) && !empty($jobcategory[0])) {
                        $where['ris.category1'] = $jobcategory[0];
                    }
                    if (isset($jobcategory[1]) && !empty($jobcategory[1])) {
                        $where['ris.category2'] = $jobcategory[1];
                    }
                    if (isset($jobcategory[2]) && !empty($jobcategory[2])) {
                        $where['ris.category3'] = $jobcategory[2];
                    }
                }
                if (!empty($trade)) {
                    $where['ris.trade'] = $trade;
                }
                if (!empty($nature)) {
                    $where['ris.nature'] = $nature;
                }
                if (!empty($minwage)) {
                    $where['ris.minwage'] = ['egt', $minwage];
                }
                if (!empty($maxwage)) {
                    $where['ris.maxwage'] = ['elt', $maxwage];
                }
            }

            // 性别筛选条件---
            if (!empty($sex)) {//审核状态
                $where['r.sex'] = ['=', $sex];
            }

            /**
             * 年龄
             * 参数:0-不限|1-16~20岁|2-20~30岁|3-30~40岁|4-40~50岁|5-50岁以上
             */
            if (!empty($age)) {
                switch ($age) {
                    case 1:
                        $where['r.birthday'] = [
                            ['<=', (date('Y') - 16)],
                            ['>=', (date('Y') - 20)]
                        ];
                        break;

                    case 2:
                        $where['r.birthday'] = [
                            ['<=', (date('Y') - 20)],
                            ['>=', (date('Y') - 30)]
                        ];
                        break;

                    case 3:
                        $where['r.birthday'] = [
                            ['<=', (date('Y') - 30)],
                            ['>=', (date('Y') - 40)]
                        ];
                        break;

                    case 4:
                        $where['r.birthday'] = [
                            ['<=', (date('Y') - 40)],
                            ['>=', (date('Y') - 50)]
                        ];
                        break;

                    case 5:
                        $where['r.birthday'] = ['<=', (date('Y') - 50)];
                        break;

                    default:
                        break;
                }
            }

            if ($tag) {
                $tag_arr = is_array($tag)
                    ? $tag
                    : explode('_', $tag);
                foreach ($tag_arr as $key => $value) {
                    $where[] = ['exp', Db::raw("FIND_IN_SET('{$value}',r.tag)")];
                }
            }

            if (!empty($major)) {//专业
                $where['r.major'] = ['=', $major];
            }

            if (!empty($settr)) {//学历
                $where['r.updatetime'] = ['egt', strtotime('-' . $settr . 'day')];
            }

            $join[] = ['resume_remark rr', 'a.resume_id=rr.resume_id and a.comid=rr.comid', 'LEFT'];
            $join[] = ['member m', 'a.personal_uid=m.uid', 'RIGHT'];

            $total = model('JobApply')->alias('a');
            foreach ($join as $k => $v) {
                $total = $total->join($v[0], $v[1], $v[2]);
            }
            $total = $total->where($where)
                ->field('r.id')
                ->group('r.id')
                ->count();

            $list = model('JobApply')->alias('a');
            foreach ($join as $k => $v) {
                $list = $list->join($v[0], $v[1], $v[2]);
            }
            $list = $list->field('a.id,a.comid,a.companyname,a.jobid,a.jobname,a.resume_id,a.fullname,a.note,a.addtime,a.is_look,a.handle_status,a.source,a.platform,r.display_name,r.high_quality,r.birthday,r.sex,r.education,r.enter_job_time,r.photo_img,r.current,r.updatetime,rr.remark,r.audit,r.uid as resume_uid,r.download_time')
                ->where($where)
                ->where('r.id', 'not null')
                ->order('r.download_time desc')
                ->order('a.id desc')
                ->page($current_page, $pagesize)
                ->select();

            //echo model('JobApply')->getLastSql();die;
            $resumeid_arr = [];
            $resumelist = [];
            $intention_arr = [];
            $photo_id_arr = [];
            $photo_data = [];
            $fullname_arr = [];
            foreach ($list as $key => $value) {
                $resumeid_arr[] = $value['resume_id'];
                $value['photo_img'] > 0 && ($photo_id_arr[] = $value['photo_img']);
                $resumeinfo[] = [
                    'id' => $value['resume_id'],
                    'uid' => $value['resume_uid']
                ];
            }
            if (!empty($photo_id_arr)) {
                $photo_data = model('Uploadfile')->getFileUrlBatch(
                    $photo_id_arr
                );
            }
            if (!empty($resumeid_arr)) {
                $intention_data = model('ResumeIntention')
                    ->where('rid', 'in', $resumeid_arr)
                    ->order('id asc')
                    ->select();
                foreach ($intention_data as $key => $value) {
                    $intention_arr[$value['rid']][] = $value;
                }
                $work_data = model('ResumeWork')
                    ->where('rid', 'in', $resumeid_arr)
                    ->order('id desc')
                    ->select();
                foreach ($work_data as $key => $value) {
                    if (isset($work_list[$value['rid']])) {
                        //只取第一份工作经历（最后填写的一份）
                        continue;
                    }
                    $work_list[$value['rid']] = $value;
                }
                $fullname_arr = model('Resume')->formatFullname($resumeid_arr, $this->userinfo);
            }
            $members = Member::whereIn('uid',array_column($list,'resume_uid'))->column('mobile','uid');
            $contacts = model('Resume')->getContactBatch($resumeinfo??[],$this->userinfo);
            $category_data = model('Category')->getCache();
            $category_job_data = model('CategoryJob')->getCache();
            $category_district_data = model('CategoryDistrict')->getCache();

            foreach ($list as $key => $value) {
                $value['remark'] = $value['remark']??'';
                $value['fullname'] = isset($fullname_arr[$value['resume_id']]) ? $fullname_arr[$value['resume_id']] : $value['fullname'];
                $value['sex_text'] = model('Resume')->map_sex[$value['sex']];
                $value['education_text'] = isset(
                    model('BaseModel')->map_education[$value['education']]
                )
                    ? model('BaseModel')->map_education[$value['education']]
                    : '';
                $value['experience_text'] =
                    $value['enter_job_time'] == 0
                        ? '无经验'
                        : format_date($value['enter_job_time']) . '经验';
                $value['current_text'] = isset(
                    $category_data['QS_current'][$value['current']]
                )
                    ? $category_data['QS_current'][$value['current']]
                    : '';
                if (isset($work_list[$value['resume_id']])) {
                    $value['recent_work'] =
                        $work_list[$value['resume_id']]['jobname'];
                } else {
                    $value['recent_work'] = '';
                }

                $value['age'] = date('Y') - intval($value['birthday']);
                $district_arr = $category_arr = [];
                if (isset($intention_arr[$value['resume_id']])) {
                    foreach ($intention_arr[$value['resume_id']] as $k => $v) {
                        if ($v['trade']) {
                            $trade_arr[] =
                                $category_data['QS_trade'][$v['trade']];
                        }
                        if ($v['nature']) {
                            $nature_arr[] = model('Resume')->map_nature[$v['nature']];
                        }
                        $wage_arr[0] = $v['minwage'] . '-' . $v['maxwage'];
                        if ($v['category']) {
                            $category_arr[] = isset(
                                $category_job_data[$v['category']]
                            )
                                ? $category_job_data[$v['category']]
                                : '';
                        } else {
                            if ($v['category_text']) {
                                $category_arr[] = $v['category_text'];
                            }
                        }
                        if ($v['district']) {
                            $district_arr[] = isset(
                                $category_district_data[$v['district']]
                            )
                                ? $category_district_data[$v['district']]
                                : '';
                        } else {
                            if ($v['district_text']) {
                                $category_district_data[] = $v['district_text'];
                            }
                        }
                    }
                }
                if (!empty($trade_arr)) {
                    $trade_arr = array_unique($trade_arr);
                    $value['intention_trade'] = implode(',', $trade_arr);
                } else {
                    $value['intention_trade'] = '';
                }
                if (!empty($category_arr)) {
                    $category_arr = array_unique($category_arr);
                    $value['intention_jobs'] = implode(',', $category_arr);
                } else {
                    $value['intention_jobs'] = '';
                }
                if (!empty($wage_arr)) {
                    $wage_arr = array_unique($wage_arr);
                    $value['intention_wage'] = implode(',', $wage_arr);
                } else {
                    $value['intention_wage'] = '';
                }
                if (!empty($district_arr)) {
                    $district_arr = array_unique($district_arr);
                    $value['intention_district'] = implode(',', $district_arr);
                } else {
                    $value['intention_district'] = '';
                }
                if (!empty($nature_arr)) {
                    $nature_arr = array_unique($nature_arr);
                    $value['intention_nature'] = implode(',', $nature_arr);
                } else {
                    $value['intention_nature'] = '';
                }
                $value['photo_img_src'] = isset(
                    $photo_data[$value['photo_img']]
                )
                    ? $photo_data[$value['photo_img']]
                    : default_empty('photo', $value['sex']);

                $value['resume_link_url_web'] = url('index/resume/show', ['id' => $value['resume_id']], true, $this->sub_site_domain);
                $value['job_link_url_web'] = url('index/job/show', ['id' => $value['jobid']], true, $this->sub_site_domain);

                /**
                 * 联系方式
                 */
//                $resumeinfo = [
//                    'id' => $value['resume_id'],
//                    'uid' => $value['resume_uid']
//                ];
//                $getResumeContact = model('Resume')->getContact($resumeinfo, $this->userinfo);
//                $getResumeContact = $contacts[$value['id']]??[];
                $getResumeContact = $contacts[$value['resume_id']]?$contacts[$value['resume_id']]:[];
                if (!empty($getResumeContact) && $getResumeContact['show_contact'] == 1) {
                    $resume_mobile = $members[$value['resume_uid']]?$members[$value['resume_uid']] :'';
                    $value['resume_contact'] = $resume_mobile;
                } else {
                    $value['resume_contact'] = 0;
                }

                $list[$key] = $value;
            }

            $return['items'] = $list;
            $return['total'] = $total;
            $return['current_page'] = $current_page;
            $return['pagesize'] = $pagesize;
            $return['total_page'] = ceil($total / $pagesize);
            $this->ajaxReturn(200, '获取数据成功', $return);
        }catch (Exception $e){
            dolog(__METHOD__,[$e->getMessage(),$e->getFile(),$e->getLine()]);
            $this->ajaxReturn(200, '系统正在努力工作中');
        }

    }

    /**
     * 查询地区
     * @return void
     */
    public function getCategoryDistrict() {
        $pid = input('get.pid/d', 0, 'intval');
        $list = model('CategoryDistrict')->getCacheWithInfo($pid);
        $this->ajaxReturn(200, '获取数据成功', $list);
    }

    /**
     * 获取查询条件
     * @return void
     */
    public function getConditions() {
        $expOptions = model('BaseModel')->map_experience;
        $categoryAll = model('Category')->getCache('');
//        $majorAll = model('CategoryMajor')->getCache('');
        $eduOptions = model('BaseModel')->map_education;
        $natureOptions = model('Resume')->map_nature;

        $res['expOptions'] = $expOptions;
        $res['tagOptions'] = $categoryAll['QS_resumetag'];
        $res['sexOptions'] = ['1' => '男', '2' => '女'];
        $res['ageOptions'] = [
            '1' => ['start' => 16, 'end' => 20, 'name' => '16-20岁'],
            '2' => ['start' => 20, 'end' => 30, 'name' => '20-30岁'],
            '3' => ['start' => 30, 'end' => 40, 'name' => '30-40岁'],
            '4' => ['start' => 40, 'end' => 50, 'name' => '40-50岁'],
            '5' => ['start' => 50, 'end' => '', 'name' => '50岁以上'],
        ];
//        $res['tradeOptions'] = $categoryAll['QS_trade'];
//        $res['majorOptions'] = $majorAll;
        $res['eduOptions'] = $eduOptions;
        $res['natureOptions'] = $natureOptions;
        $res['wageOptions'] = [
            '1' => ['start' => 0, 'end' => 1000, 'name' => '1000元以下'],
            '2' => ['start' => 1000, 'end' => 2000, 'name' => '1000-2000元'],
            '3' => ['start' => 2000, 'end' => 3000, 'name' => '2000-3000元'],
            '4' => ['start' => 3000, 'end' => 5000, 'name' => '3000-5000元'],
            '5' => ['start' => 5000, 'end' => 8000, 'name' => '5000-8000元'],
            '6' => ['start' => 8000, 'end' => 12000, 'name' => '8000-12000'],
            '7' => ['start' => 12000, 'end' => 15000, 'name' => '12000-15000'],
            '8' => ['start' => 15000, 'end' => '', 'name' => '15000元以上'],
        ];
        $res['timeOptions'] = [
            '1' => ['day' => 3, 'name' => '3天'],
            '2' => ['day' => 7, 'name' => '7天'],
            '3' => ['day' => 15, 'name' => '15天'],
            '4' => ['day' => 30, 'name' => '30天'],
        ];
        $res['recruit_platform'] = array_column($this->recruit_platform,'name');
        $this->ajaxReturn(200, '获取数据成功', $res);
    }

    /**
     * 上传简历
     * @return void
     */
    public function upload() {
        $file = input('file.file');
        if (!$file) {
            $this->ajaxReturn(500, '请选择文件');
        }
        $config = ['fileupload_ext' => 'docx,pdf,xlsx', 'uploadfile_dir' => 'resume'];
        $filemanager = new \app\common\lib\FileManager($config);
        $res = $filemanager->uploadReturnPath($file);
        if (false !== $res) {
            $file = SYS_UPLOAD_PATH . $res['save_path'];
            $dataList = ResumeParseLogic::fileParse($file);
            if (empty($dataList) || !empty($dataList['code'])) {
                $this->ajaxReturn(500, $dataList['msg']??'解析失败',$dataList['data']??null);
            }else{
                file_exists($file) && unlink($file);
            }

           $res = ResumeLogic::import($dataList, $this->company_profile['id']);
            if (empty($res) || !empty($res['code'])) {
                $this->ajaxReturn(500, $res['msg']??'导入失败',$res['data']??null);
            }
            $this->ajaxReturn(200, '导入成功', $res);
        } else {
            $this->ajaxReturn(500, $filemanager->getError());
        }
    }
    /**
     * 上传简历
     * @return false|string
     */
    public function uploadZip() {
        $file = input('file.file');
        if (!$file) {
            $this->ajaxReturn(500, '请选择文件');
        }
        $config = ['fileupload_ext' => 'zip,rar'];
        $filemanager = new \app\common\lib\FileManager($config);
        $res = $filemanager->uploadReturnPath($file);
        if(!$res){
            return $this->returnJson(500,$filemanager->getError());
        }
        $path_info = pathinfo(SYS_UPLOAD_PATH . $res['save_path']);
        try{
            $archive = BaseArchiveLogic::make($path_info['extension'])->open(SYS_UPLOAD_PATH . $res['save_path']);
            $dir = preg_replace('/\.'.$path_info['extension'].'/','',SYS_UPLOAD_PATH . $res['save_path']);
            $res = $archive
                ->extractTo($dir)
                ->getFiles();
            $archive->close();
        }catch (\Exception $e){
            return $this->returnJson(500,'压缩包解析失败');
        }


        if(count($res) <= 0){
            return $this->returnJson(500,'暂无有效简历文件');
        }
        $error = [];
        $dataList = [];

        foreach($res as $v){
            $data = ResumeParseLogic::fileParse($v);
            if (empty($data) || !empty($data['code'])) {
                $error[] = ['file'=>$v,'error_msg'=>$data['msg']??'解析失败'];
                continue;
            }else{
                unlink($v);
            }
            $dataList = array_merge($dataList,$data);
        }

//        try{rmdirs($dir,true);}catch(Exception $e){dolog(__METHOD__.':rmdirs',[$e->getMessage()]);}

        if(empty($dataList)){
            return $this->returnJson(500,'解析失败',$error);
        }

        $res = ResumeLogic::import($dataList, $this->company_profile['id']);
        if (empty($res)) {
//            $error[] = ['file'=>$v,'error_msg'=>'导入失败'];
            return $this->returnJson(500,'导入失败');
        }
        return $this->returnJson(200,'导入成功',['error'=>$error]);
    }

    public function downloadResumeTpl() {
        $url = config('global_config.sitedomain') . DS . 'upload/resource/import_resume_tpl.xlsx';
        $this->ajaxReturn(200, '', $url);
    }
    public function downloadResumePlugin() {
        $url = config('global_config.sitedomain') . DS . 'upload/resource/extension.zip?t='.date('Ymd');
        $this->ajaxReturn(200, '', $url);
    }

    /**
     * 数据统计
     * @return void
     * @throws \think\Exception
     */
    public function report() {
        $where['comid'] = $this->company_profile['id'];
        $where['company_id'] = $this->company_profile['id'];
        $total = model('JobApply')->alias('j')
            ->join('member m', 'm.uid = j.personal_uid','right')
            ->where($where)->count();

        $where['addtime'] = ['gt', strtotime(date('Ymd'))];
        $new = model('JobApply')->alias('j')->join('member m', 'm.uid = j.personal_uid','right')->where($where)->count();
        $month = model('JobApply')->alias('j')->join('member m', 'm.uid = j.personal_uid','right')
            ->where($where)->whereTime('addtime', 'month')->count();
        $return['total'] = $total;
        $return['new'] = $new;
        $return['active'] = $month;
        $return['activate_num'] = ResumeActivate::getNum($this->company_profile['id']);
        $this->ajaxReturn(200, '获取数据成功', $return);
    }

    public function activateRefresh(){
        $res = ResumeActivate::handle($this->company_profile['id']);
        return $this->returnJson($res['code'],$res['msg'],$res['data']);
    }
    /**
     * 导出简历
     * @return void
     * @throws \EasyZip\Exception\ZipException
     */
    public function export() {
        $ids = input('get.ids/a', []);
        $zipFile = new ZipFile();
        foreach ($ids as $id) {
            $file = ResumeLogic::exportPdf($id);
            if (!$file) {
                continue;
            }
            $zipFile->addFile($file);
        }
        $zipPath = SYS_UPLOAD_DIR_NAME . DS . 'resumePdf' . DS . date('Ym') . DS . uniqid() . '.zip';
        $zipFile->saveAsFile($zipPath)->close();
        $url = config('global_config.sitedomain') . DS . $zipPath;
        $this->ajaxReturn(200, '获取数据成功', $url);
    }


    /**
     * 获取口令数据
     */
    public function get_secretkey(){
        $action = input('action/s');
        $company_id = Company::where(['uid'=>$this->userinfo->uid])->value('id');
        $redis_name = 'get_secretkey_'.$company_id;
        $redis = new Redis();
        $callback = function()use($redis_name,$company_id,$redis){
            $secretKey = $this->passport_encrypt(json_encode(['id'=>$company_id,'time'=>time()]));
            $redis->set($redis_name,$secretKey);
            return $secretKey;
        };
        switch ($action){
            case 'create':
                $secretKey = call_user_func($callback);
                break;
            default:
                $secretKey = $redis->get($redis_name)?:'';
        }

        $this->ajaxReturn(200, '获取成功',$secretKey);
    }

    /**
     * 密钥验证接口
     * @return void
     */
    public function verify_secretkey(){
        $secretKey = input('post.secretkey');
        $info = [];
        //$secretKey = 'Vcmb4YarX\/jzER65gzjXaQ==';
        $res = $this->passport_decrypt($secretKey);
        $id = json_decode($res,1);
        $ret = Db::name('company')->field('id,companyname')->where(['id'=>$id['id'],'is_display'=>1])->find();
        $info = $ret;
        $info['secretKey'] = $secretKey;
        if(isset($ret)){
            return $this->returnJson(200, '验证成功',$info);
        }else{
            $this->ajaxReturn(500, '验证失败');
        }

    }

    public function test()
    {
        $this->ajaxReturn(200, '导入成功111', []);
    }

    /**
     * 插件导入接口
     * @return void
     */
    public function google_plug_import(){
//        $secretKey = input('post.secretKey');
        $res_verify = json_decode($this->verify_secretkey(),1);
        $company_id = $res_verify['data']['id'];
        $content = $_POST['content'];
        $arr = json_decode($content,true);
//        $company_id = $this->passport_decrypt($secretKey);
//        $ret = Db::name('company')->field('id,companyname')->where(['id'=>$company_id,'is_display'=>1])->find();
//        if (!isset($ret))
//            $this->ajaxReturn(500, '密钥错误！');
       // $company_id = 4;//默认导入公司的ID
        $res = ResumeLogic::import($arr,$company_id);
        if (empty($res)) {
            $this->ajaxReturn(500, '导入失败');
        }
        $this->ajaxReturn(200, '导入成功', $res);


    }

    public function thirdUploadGetMobile(){
        $res_verify = json_decode($this->verify_secretkey(),1);
        $this->company_profile['id'] = $res_verify['data']['id'];

        $file = input('file.file');
        if(!$file){
            return $this->returnJson(500,'请上传文件');
        }
        $config = ['fileupload_ext' => 'docx,pdf,xlsx', 'uploadfile_dir' => 'resume'];
        $filemanager = new \app\common\lib\FileManager($config);
        $res = $filemanager->uploadReturnPath($file);
        if (false !== $res) {

            $file = SYS_UPLOAD_PATH . $res['save_path'];
            $path_info = pathinfo($file);

            $actions = ['docx'=>'pythonWordParseTime','pdf'=>'pythonPdfParseTime'];
            $action = $actions[strtolower($path_info['extension'])];

            $res = call_user_func([ResumeParseLogic::class,$action],$file);
            if(is_array($res)){
                $res = current(preg_grep('/1[3-9]\d(-)?\d{4}(-)?\d{4}/',$res));
            }
            // 提取手机号
            preg_match('/1[3-9]\d(-)?\d{4}(-)?\d{4}/',$res,$match);
            if(file_exists($file)){
                unlink($file);
            }
        }
        if(!$mobile = $match[0]??''){
            return $this->returnJson(500,'未解析到手机号');
        }
        return $this->returnJson(200,'success',preg_replace('/-/','',$mobile));
    }
    public function thirdUploadGetMobileBatch(){
        $res_verify = json_decode($this->verify_secretkey(),1);
        $this->company_profile['id'] = $res_verify['data']['id'];

        $files = input('file.file');

        if(!$files){
            return $this->returnJson(500,'请上传文件');
        }
        $config = ['fileupload_ext' => 'docx,pdf,xlsx', 'uploadfile_dir' => 'resume'];
        $filemanager = new \app\common\lib\FileManager($config);
        foreach ($files as $file){
            $file_info = $file->getInfo();
            $res = $filemanager->uploadReturnPath($file);
            if (false !== $res) {

                $file = SYS_UPLOAD_PATH . $res['save_path'];
                $path_info = pathinfo($file);

                $actions = ['docx'=>'pythonWordParseTime','pdf'=>'pythonPdfParseTime'];
                $action = $actions[strtolower($path_info['extension'])];

                $res = call_user_func([ResumeParseLogic::class,$action],$file);
                if(is_array($res)){
                    $res = current(preg_grep('/1[3-9]\d(-)?\d{4}(-)?\d{4}/',$res));
                }
                // 提取手机号
                preg_match('/1[3-9]\d(-)?\d{4}(-)?\d{4}/',$res,$match);
                if(file_exists($file)){
                    unlink($file);
                }
                if(!$mobile = $match[0]??''){
                    $error[] = $file_info['name'];
                    continue;
                }
                $mobile = preg_replace('/-/','',$mobile);
                $result[] = $mobile;
            }

        }

        return $this->returnJson(200,'success',['result'=>$result??[],'error'=>$error??[]]);
    }
    public function thirdUploadGetMobileZip(){
        $res_verify = json_decode($this->verify_secretkey(),1);
        $this->company_profile['id'] = $res_verify['data']['id'];

        $file = input('file.file');

        if(!$file){
            return $this->returnJson(500,'请上传文件');
        }
        $config = ['fileupload_ext' => 'zip,rar'];
        $filemanager = new \app\common\lib\FileManager($config);
        $res = $filemanager->uploadReturnPath($file);
        if(!$res){
            return $this->returnJson(500,$filemanager->getError());
        }
        $path_info = pathinfo(SYS_UPLOAD_PATH . $res['save_path']);

        $archive = BaseArchiveLogic::make($path_info['extension'])->open(SYS_UPLOAD_PATH . $res['save_path']);
        $dir = preg_replace('/\.'.$path_info['extension'].'/','',SYS_UPLOAD_PATH . $res['save_path']);
        $res = $archive
            ->extractTo($dir)
            ->getFiles();
        $archive->close();

        if(count($res) <= 0){
            return $this->returnJson(500,'暂无有效简历文件');
        }

        foreach ($res as $file){
            $path_info = pathinfo($file);

            $actions = ['docx'=>'pythonWordParseTime','pdf'=>'pythonPdfParseTime'];
            $action = $actions[strtolower($path_info['extension'])];

            $res = call_user_func([ResumeParseLogic::class,$action],$file);
            if(is_array($res)){
                $res = current(preg_grep('/1[3-9]\d(-)?\d{4}(-)?\d{4}/',$res));
            }
            // 提取手机号
            preg_match('/1[3-9]\d(-)?\d{4}(-)?\d{4}/',$res,$match);
            if(!$mobile = $match[0]??''){
                $error[] = $file;
                continue;
            }
            $mobile = preg_replace('/-/','',$mobile);
            $result[] = $mobile;
            if(file_exists($file)){
                unlink($file);
            }
        }

        return $this->returnJson(200,'success',['result'=>$result??[],'error'=>$error??[]]);
    }
    public function thirdUploadZip(){
        $res_verify = json_decode($this->verify_secretkey(),1);
        $this->company_profile['id'] = $res_verify['data']['id'];

        $res = json_decode($this->uploadZip(),1);
        if(!empty($res['data']['error'])){
            return $this->returnJson(500,'有解析失败文件',$res['data']);
        }
        return $this->returnJson(200,'导入成功',$res['data']);
    }
    public function thirdUploadDir(){
        $res_verify = json_decode($this->verify_secretkey(),1);
        $this->company_profile['id'] = $res_verify['data']['id'];
        $files = input('file.file');
        if(!$files){
            return $this->returnJson(500,'请上传文件');
        }
        $config = ['fileupload_ext' => 'docx,pdf,xlsx,zip,rar', 'uploadfile_dir' => 'resume'];
        $dataList = [];
        foreach($files as $file){
            $filemanager = new \app\common\lib\FileManager($config);
            $res = $filemanager->uploadReturnPath($file);
            if (false !== $res) {
                $file = SYS_UPLOAD_PATH . $res['save_path'];
                $data = ResumeParseLogic::fileParse($file);
                if (empty($data) || !empty($data['code'])) {
                    unlink($file);
                    $error[] = ['file'=>$file,'error_msg'=>$data['msg']??'解析失败'];
                    continue;
                }
                $dataList = array_merge($dataList,$data);
            }
        }
        if(empty($dataList)){
            return $this->returnJson(500,'解析失败');
        }
        $res = ResumeLogic::import($dataList, $this->company_profile['id']);
        if (empty($res)) {
//            $error[] = ['file'=>$v,'error_msg'=>'导入失败'];
            return $this->returnJson(200,'导入失败');
        }
        return $this->returnJson(200, '导入成功', $res);
    }
}
